//edit question
$('.btn-edit').on('click',function(){
    $('.question-form').toggle();
    $('.question').toggle();
    var space=$('.question-space').text().trim();
    $('[name="space"][value="'+space+'"]').prop('checked','checked');
});

//delete question
$('.btn-delete').on('click',function(){
    var qid=$(this).parent().data('id');
    $.ajax({
        url:'/question',
        type:"DELETE",
        data:{
            qid
        }
    }).done(function(res){
        if(res.success){
            location.href='/'
        }else{
            alert(res.msg);
        }
    }).fail(function(xhr){
        alert('delete fail');
    });
})


//update question
$('.btn-question-submit').on('click',function(){
    var title = $('[name="title"]').val().trim();
    var space = $('[name="space"]:checked').val()
    var content = $('[name="content"]').val().trim();
    var qid=$('.btn-edit').parent().data('id');
    if(!title){
       showMsg($('.error-info'),'Please input title');
       return
    }

    if(!space){
       showMsg($('.error-info'),'Please select space');
       return
    }

    if(!content){
        showMsg($('.error-info'),'Please  input content');
        return
    }


    $.ajax({
        url:'/question',
        type:'PUT',
        data:{
            qid:qid,
            title,
            space,
            content
        }
    }).done(function(res){
        if(res.success){
           window.location.href='/';
        }else{
           showMsg($('.error-info'),'email or password error');
        }
    }).fail(function(xhr){
        showMsg($('.error-info'),'Server error');
        console.log(xhr)
    });

});

//cancel edit question 
$('.btn-question-cancel').on('click',function(){
    $('.question-form').toggle();
    $('.question').toggle();
});

//show answer
$('.small-answer').on('click',function(){
    $('.answer').show();
})



//post answer
$('.post-answer,.btn-answer-cancel').on('click',function(){
    $('.answer-form').toggle();
    $('.user-tooltip').toggle();
});

//delete answer
$('.btn-answer-delete').on('click',function(){
    var aid=$(this).data('id');
    var dom=$(this);
    $.ajax({
        url:'/answer',
        type:'DELETE',
        data:{
            aid
        }
    }).done(function(res){
        if(res.success){
               dom.parent().remove();
                var num=parseInt($('.answer-number').text())
                $('.answer-number').text(num-1);
        }else{
             alert(res.msg||'delete answer fail')
        }
    }).fail(function(xhr){
        alert('server error');
    });
})
